#include "cconexao.h"

CConexao::CConexao(QObject *parent) :
    QObject(parent)
{    
    QObject::connect(&_net, SIGNAL(finished(QNetworkReply*)), this, SLOT(termino(QNetworkReply*)));    
    _net.setCookieJar(&_jar);
}

CConexao::~CConexao()
{
}

void CConexao::Consultar(const QString &url, const QByteArray &data, bool get, const QString &referer)
{
    QNetworkRequest req;
    req.setUrl(url);
    qDebug() << "Consultar " << url;
    req.setRawHeader("Accept", "*/*");
    if (referer != "") {
        qDebug() << " Referer ::::: " << referer;
        QByteArray arr;
        arr.append(referer);
        req.setRawHeader("Referer", arr);
    }
    //req.setRawHeader("Accept-Encoding", "gzip");
    req.setRawHeader("Accept-Language", "pt-BR");
    req.setRawHeader("Connection", "Keep-Alive");
    req.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36");
    if (get)
        _net.get(req);
    else {
        req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        _net.post(req, data);
    }    
}

void CConexao::termino(QNetworkReply *rep)
{    
    QString tipo = rep->header(QNetworkRequest::ContentTypeHeader).toString();
    qDebug() << "tipo do documento " << tipo;
    QByteArray arr = rep->readAll();
    if (arr.length() == 0)
        emit erroConexao();
    else if (tipo.contains("text", Qt::CaseInsensitive))
         emit texto(arr);
    else
        emit conteudoBinario(tipo, arr);    
    rep->deleteLater();
}




